package com.example.sangong.schedule;

import cn.hutool.core.util.StrUtil;
import com.example.sangong.demo.service.WebSocketServer;
import com.example.sangong.websocket.WebSocketMessage;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Slf4j
public class SendMessageSchedule {
    @Resource
    private WebSocketServer webSocketServer;


    /**
     * 半个小时发送一次
     */
    @Scheduled(cron = "0 0/30 * * * ?")
    public void execute() {

        String time = getSystemTime();
        WebSocketMessage message = new WebSocketMessage();
        message.setSender("system");
        message.setContent("欢迎来到我的页面，现在时间是:" + time);
        log.info("定时发送的消息为:{}", message);
        webSocketServer.sendMessage(message);


    }

    @XxlJob("sendSystemMsgJob")
    public void sendSystemMsgJob() {
        //获取参数
        String param = XxlJobHelper.getJobParam();
        log.info("系统掺入的参数为:{}", param);
        String time = getSystemTime();
        WebSocketMessage message = new WebSocketMessage();
        message.setSender("xxl-job");
        StringBuilder msg = new StringBuilder("欢迎来到我的页面，现在时间是:");
        msg.append(time).append("。");
        if (StrUtil.isNotBlank(msg)) {
            msg.append(param);
        }
        message.setContent(msg.toString());
        log.info("xxl-job定时发送的消息为:{}", message);
        webSocketServer.sendMessage(message);


    }

    private static String getSystemTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());
        return time;
    }
}
